<?php

namespace App\Repositories\Article;

use App\Models\ArticleCategory;
use App\Repositories\BaseRepository;

/**
 * Class ArticleCategoryRepository
 * @package App\Repositories\Article
 * @method ArticleCategory|null getById($id)
 * @method ArticleCategory create(array $attributes)
 */
class ArticleCategoryRepository extends BaseRepository
{
    public function __construct(ArticleCategory $model)
    {
        parent::__construct($model);
    }

    public function tree(): array
    {
        $categories = $this->query()->orderByDesc('id')->get()->map(fn(ArticleCategory $item) => [
            'id' => $item->id,
            'parent_id' => $item->parent_id,
            'name' => $item->name,
            'slug' => $item->slug,
            'description' => $item->description,
            'sort' => $item->sort,
            'status' => $item->status,
            'created_at' => $item->created_at->format('Y-m-d'),
        ])->toArray();
        return $this->buildTree($categories);
    }

    public function getSelect(): array
    {
        $categories = ArticleCategory::query()->orderByDesc('id')->get(['id','parent_id', 'name'])->toArray();
        return $this->buildTree($categories);
    }

    public function buildTree($categories, $parentId = 0): array
    {
        $tree = [];
        foreach ($categories as $category) {
            if ($category['parent_id'] == $parentId) {
                $children = $this->buildTree($categories, $category['id']);
                if ($children) {
                    $category['children'] = $children;
                }
                $tree[] = $category;
            }
        }
        return $tree;
    }
}
